﻿using System.ComponentModel;
using JBeamLibrary.Events;
using JBeamLibrary.VehicleParts.Elements;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JBeamLibrary.VehicleParts.Interfaces;

namespace JBeamLibrary.VehicleParts.Collections
{
    public class TriangleCollection : Collection<Triangle>, IVehicleGroupCollection<Triangle>
    {
        #region Fields

        public event EventHandler<Triangle> TriangleAdded;
        public event EventHandler TriangleRemoved;
        public event ElementPropertyChangedEventHandler ElementPropertyChanged;

        #endregion

        #region Indexers

        #endregion

        #region CTORs

        /// <summary>Creates a new triangle collection</summary>
        public TriangleCollection() { }

        /// <summary>Creates a new triangle collection</summary>
        /// <param name="triangles"></param>
        public TriangleCollection(IEnumerable<Triangle> triangles)
        {
            AddRange(triangles);
        }

        #endregion

        #region Methods

        public new void Add(Triangle triangle)
        {
            base.Add(triangle);

            triangle.PropertyChanged += (s, e) =>
            {
                if (ElementPropertyChanged != null)
                    ElementPropertyChanged(s, e);
            };

            if (TriangleAdded != null)
                TriangleAdded(this, triangle);
        }

        public void Add(string nodeId1, string nodeId2, string nodeId3)
        {
            Add(new Triangle(nodeId1, nodeId2, nodeId3));
        }

        public void Add(Node node1, Node node2, Node node3)
        {
            Add(node1.Id, node2.Id, node3.Id);
        }

        public void AddRange(IEnumerable<Triangle> triangles)
        {
            foreach (var triangle in triangles)
                Add(triangle);
        }

        public void Remove(string nodeId1, string nodeId2, string nodeId3)
        {
            for (var i = 0; i < Count; i++)
            {
                var triangle = this[i];
                if (!triangle.NodeId1.Equals(nodeId1) || !triangle.NodeId2.Equals(nodeId2) || !triangle.NodeId3.Equals(nodeId3))
                    continue;

                RemoveAt(i);
                i--;
            }
        }

        public new void Remove(Triangle element)
        {
            base.Remove(element);

            if (TriangleRemoved != null)
                TriangleRemoved(this, new EventArgs());
        }

        #endregion
    }
}
